package com.cola.dao;

import com.cola.entity.mep.Mep;
import com.cola.entity.order.Order;
import com.cola.entity.order.OrderDetail;
import com.cola.enums.OrderType;
import com.cola.utils.DBControl;
import com.cola.utils.DateUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * 类名：MepDao
 * 功能：经销商dao
 * 作者：Tony
 * 日期：2017/8/30.
 */
public class MepDao extends BaseDao {
    private final Logger logger =  LoggerFactory.getLogger(getClass());

    private static MepDao MepDao = new MepDao();

    private MepDao(){}

    public static MepDao getInstance(){
        return MepDao;
    }

    /**
     * 功能：获取区域内的所有经销商信息
     * 参数：所在区域
     * 返回：所在区域的所有经销商信息
     */
    public List<Map<String,Object>> getMepInfoByArea(String area){
        Connection conn = null;
        try {
            conn = DBControl.getConnection();
            String sql = "select * from cola_mep where area = ? ";
            return getQueryRunner().query(conn,sql, new MapListHandler(),area);
        } catch (Exception e) {
            logger.error("获取区域内的经销商信息失败！",e);
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return null;
    }

    /**
     * 功能：获取区域内经销商信息
     * 参数：所在区域
     * 返回：所在区域的所有经销商信息
     */
    public List<Mep> getMepInfoByCityNo(String cityNo){
        Connection conn = null;
        try {
            conn = DBControl.getConnection();
            String sql = "select * from cola_mep where city = ? and is_bind =1 and status =1 ";
            return getQueryRunner().query(conn,sql,new BeanListHandler<Mep>(Mep.class),cityNo);
        } catch (Exception e) {
            logger.error("获取区域内的经销商信息失败！",e);
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return null;
    }

    /**
     * 功能：获取推荐经销商列表
     * 参数：所在区域
     * 返回：所在区域的所有经销商信息
     */
    public List<Mep> getRecommendMepByCustomerNo(String customerNo){
        Connection conn = null;
        try {
            conn = DBControl.getConnection();
            String sql = "SELECT b.* FROM `cola_recommend_mep` a " +
                    "INNER JOIN cola_mep b on a.mep_no = b.mep_no  where a.customer_system_no = ? and b.is_bind =1 and b.status =1 ";
            return getQueryRunner().query(conn,sql,new BeanListHandler<Mep>(Mep.class),customerNo);
        } catch (Exception e) {
            logger.error("获取区域内的经销商信息失败！",e);
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return null;
    }



    /**
     * 功能：根据经销商编号获取经销商信息
     * 参数：经销商编号
     * 返回：经销商信息
     */
    public Mep getMepInfoByMepNo(String mepNo){
        Connection conn=null;
        try {
            conn = DBControl.getConnection();
            String sql = "select a.*,b.area_name as city_name,c.area_name as area_name from cola_mep a " +
                    " left join system_area b on a.city = b.area_no" +
                    " left join system_area c on a.area = c.area_no where mep_no = ? ";
            return getQueryRunner().query(conn,sql, new BeanHandler<Mep>(Mep.class),mepNo);
        } catch (Exception e) {
            logger.error("获取经销商信息异常！",e);
        } finally {
            DbUtils.closeQuietly(conn);
        }

        return null;
    }


    /**
     * 分配配送员
     * @param orderNo 订单编号
     * @param courierId 配送员id
     * @return true 成功;false 失败
     * @author Max
     * @since 2017/9/19
     */
    public boolean setCourier(String orderNo,Integer courierId){
        Connection conn = null;
        try{
            conn = DBControl.getConnection();
            String sql = "update cola_order set order_status =? ,courier_id =? where order_no =?";
            return getQueryRunner().update(conn,sql, OrderType.WAITING_FOR_DELIVERY.getValue(),courierId,orderNo)>0;
        }catch (Exception e){
            logger.error("分配配送员异常！",e);
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return false;
    }

    /**
     * 拒单
     * @param orderNo 订单号
     * @param mepNo 经销商编号
     * @param reason 拒单原因
     * @param messageId 消息id
     * @return true 成功;false 失败
     * @author Max
     * @since 2017/9/19
     */
    public boolean rejectOrder(String orderNo,String mepNo,String reason,Integer messageId){
        Connection conn = null;
        try{
            conn = DBControl.getConnection();
            conn.setAutoCommit(false);
            boolean a = doRejectOrder(conn,orderNo,mepNo);

            boolean b = deleteOrderMessage(conn,messageId);

            boolean c = addRejectLog(conn,orderNo,reason,mepNo);

            conn.commit();
            return a && b && c;
        }catch (Exception e){
            logger.error("拒单异常！",e);
            if(conn!=null){
                try{
                    conn.rollback();
                }catch (Exception w){
                    logger.error("拒单回滚异常！",e);
                }
            }
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return false;
    }

    /**
     * 拒单操作
     * @param conn 链接
     * @param orderNo 订单号
     * @param mepNo 经销商编号
     * @return true 成功;false 失败
     * @author Max
     * @since 2017/9/19
     * @throws Exception
     */
    private boolean doRejectOrder(Connection conn,String orderNo,String mepNo) throws Exception {
        try{
            String sql = "update cola_order set order_status =?,mep_no=-1 where order_no =? and mep_no =?";
            return getQueryRunner().update(conn,sql,OrderType.WAITING_SET_NEW_MWP.getValue(),orderNo,mepNo)>0;
        }catch (Exception e){
            logger.error("拒单操作异常！",e);
            throw e;
        }
    }

    /**
     * 删除订单消息
     * @param conn
     * @param messageId
     * @return true 成功;false 失败
     * @author Max
     * @since 2017/9/19
     */
    private boolean deleteOrderMessage(Connection conn,Integer messageId) throws Exception {
        try{
            String sql = "delete from cola_order_message where message_id =?";
            return getQueryRunner().update(conn,sql,messageId)>0;
        }catch (Exception e){
            logger.error("删除订单消息异常！",e);
            throw e;
        }
    }

    /**
     * 添加拒单日志
     * @param conn
     * @param mepNo
     * @param reason
     * @param orderNo
     * @return true 成功;false 失败
     * @author Max
     * @since 2017/9/19
     */
    private boolean addRejectLog(Connection conn,String mepNo,String reason,String orderNo) throws Exception {
        try{
            String sql = "insert into cola_reject_order_log(mep_no,order_no,reject_content,create_time) values(?,?,?,?)";
            return getQueryRunner().update(conn,sql,mepNo,orderNo,reason, DateUtils.getCurrentDateTime())>0;
        }catch (Exception e){
            logger.error("添加拒单日志异常！",e);
            throw e;
        }
    }


    /**
     * 接单
     * @param orderNo 订单号
     * @param mepNo 经销商编号
     * @return true 成功;false 失败
     * @author Max
     * @since 2017/9/19
     */
    public boolean acceptOrder(String orderNo,String mepNo,Integer messageId){
        Connection conn = null;
        try{
            conn = DBControl.getConnection();
            conn.setAutoCommit(false);
            String sql = "update cola_order set order_status =? where order_no =? and mep_no =?";
            boolean a = getQueryRunner().update(conn,sql,OrderType.WAITING_ALLOCATION_COURIER.getValue(),orderNo,mepNo)>0;

            String sql2 = "update cola_order_message set check_status =? where message_id =?";

            boolean b = getQueryRunner().update(conn,sql2,1,messageId)>0;
            conn.commit();
            return a && b;
        }catch (Exception e){
            logger.error("接单异常！",e);
            if(conn!=null){
                try{
                    conn.rollback();
                }catch (Exception w){
                    logger.error("接单回滚异常！",w);
                }
            }
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return false;
    }

    //==================================订单=============================================

    /**
     * 获取订单列表
     * @param mepNo 经销商编号
     * @author Max
     * @since 2017/9/17
     */
    public List<Order> getMepOrderList(String mepNo){
        Connection conn = null;
        try{
            conn = DBControl.getConnection();
            String sql = "select a.*,b.courier_name,b.courier_mobile,c.customer_name  from cola_order a left join cola_courier b on a.courier_id = b.courier_id " +
                    " left join cola_customer c on a.customer_id = c.customer_id " +
                    " where a.mep_no =? and a.order_status<>'WAITING_FOR_RECEIVING_ORDER' order by a.create_time desc";
            return getQueryRunner().query(conn,sql,new BeanListHandler<Order>(Order.class),mepNo);
        }catch (Exception e){
            logger.error("获取全部Mep订单列表异常！",e);
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return null;
    }

    /**
     * 获取订单详情列表
     * @param mepNo 经销商编号
     * @return List<OrderDetail>
     * @author Max
     * @since 2017/9/17
     */
    public List<OrderDetail> getMepOrderDetailList(String mepNo){
        Connection conn = null;
        try{
            conn = DBControl.getConnection();
            String sql = "select * from cola_order_detail where mep_no =? ";
            return getQueryRunner().query(conn,sql,new BeanListHandler<OrderDetail>(OrderDetail.class),mepNo);
        }catch (Exception e){
            logger.error("获取全部Mep订单列表异常！",e);
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return null;
    }


    //===================================个人中心===========================================





    public static void main(String[] args){
       // System.out.print("新增的配送员的ID为："+getInstance().saveCourierInfo("测试",(long)34,"123456677"));;
       //getInstance().getMepInfoByMepId((long)34);
    }
}
